package com.sunny.blog.controller;

import cn.hutool.core.collection.IterUtil;
import cn.hutool.json.JSONArray;
import cn.hutool.json.JSONObject;
import cn.hutool.json.JSONUtil;
import com.sunny.blog.common.annotation.RequiredLogin;
import com.sunny.blog.common.entity.Response;
import com.sunny.blog.common.entity.ResponseResult;
import com.sunny.blog.service.ICacheService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletRequest;
import java.util.Set;

/**
 * @ClassName: CacheController
 * @Description:
 * @Author: sunt
 * @Date: 2020/4/23 15:59
 * @Version 1.0
 **/
@RestController
@RequestMapping("cache")
@Slf4j
public class CacheController {

    @Autowired
    private ICacheService cacheService;

    @PostMapping("queryCacheInfo")
    @RequiredLogin(required = true)
    public String queryCacheInfo(HttpServletRequest request) {
        JSONObject jsonObject = new JSONObject();
        try {
            Set<String> cacheInfo = cacheService.getCacheInfo();
            if(IterUtil.isEmpty(cacheInfo)) {
                jsonObject.put("code",999);
                jsonObject.put("msg","暂无缓存数据");
                jsonObject.put("count",0);
                return JSONUtil.toJsonStr(jsonObject);
            }
            JSONArray dataArray = new JSONArray();
            for (String s : cacheInfo) {
                JSONObject objData = new JSONObject();
                objData.put("cacheKey",s);
                dataArray.put(objData);
            }
            jsonObject.put("code",0);
            jsonObject.put("msg","查询成功");
            jsonObject.put("count",cacheInfo.size());
            jsonObject.put("data",dataArray);
            return JSONUtil.toJsonStr(jsonObject);
        } catch (Exception e) {
            jsonObject.put("code",999);
            jsonObject.put("msg","系统异常");
            jsonObject.put("count",0);
            return JSONUtil.toJsonStr(jsonObject);
        }
    }


    @GetMapping("flushAll")
    @RequiredLogin(required = true)
    public ResponseResult<String> flushAll() {
        try {
            cacheService.flushAll();
            return Response.makeOKRsp("清除缓存成功");
        } catch (Exception e) {
            e.printStackTrace();
            return Response.makeErrRsp();
        }
    }
}
